package product;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

public class SaleUpdate extends JInternalFrame{

	ArrayList<ProductData> pro;
	Vector<String> vec;
	DefaultTableModel model;
	int saleCnt;
	int index = -1;// 마우스클릭된 정보가 ArrayList어디에 위치해있는지를 찾아서 저장
	DecimalFormat df = new DecimalFormat("###,###,###.##");
	ArrayList<SaleData> aSal;
	HashMap<String, SaleTotal> hSal;
	HashMap<String, StockData> sto;

	private JPanel contentPane;
	private JLabel label;
	private JLabel lblNewLabel;
	private JLabel lblNewLabel_2;
	private JLabel lblNewLabel_3;
	private JLabel lblNewLabel_4;
	private JLabel label_2;
	private JButton btnModi;
	private JButton btnAll;
	private JLabel lblNo;
	private JTextField saleCount;
	private JTextField proCode;
	private JTextField proName;
	private JTextField saleDate;
	private JTextField saleEa;
	private JTextField saleTot;
	private JTextField proPrice;
	private JTextField stock;
	private JLabel label_1;
	int hap, stoc;

	public SaleUpdate(Vector<String> v, DefaultTableModel m,
			ArrayList<SaleData> a, HashMap<String, SaleTotal> h, int i,
			HashMap<String, StockData> s) {
		super("수정",true,true,true,false);
		this.vec = v;
		this.model = m;
		this.aSal = a;
		this.hSal = h;
		this.index = i;
		this.sto = s;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 228, 301);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getLabel());
		contentPane.add(getLblNewLabel());
		contentPane.add(getLblNewLabel_2());
		contentPane.add(getLblNewLabel_3());
		contentPane.add(getLblNewLabel_4());
		contentPane.add(getProCode());
		contentPane.add(getProName());
		contentPane.add(getSaleDate());
		contentPane.add(getSaleEa());
		contentPane.add(getSaleTot());
		contentPane.add(getBtnModi());
		contentPane.add(getBtnAll());
		contentPane.add(getLblNo());
		contentPane.add(getSaleCount());
		contentPane.add(getLabel_2());
		contentPane.add(getTextField_7());
		contentPane.add(getStock());
		contentPane.add(getLabel_1());

		saleCount.setText(vec.get(6));
		proCode.setText(vec.get(0));
		proName.setText(vec.get(1));
		saleDate.setText(vec.get(5));
		saleEa.setText(vec.get(3));
		saleTot.setText(vec.get(4));
		proPrice.setText(vec.get(2));
		int ab = sto.get(vec.get(0)).getProEa();
		stock.setText(ab + "");

		stoc = Integer.parseInt(stock.getText());// 재고량
		int bef = Integer.parseInt(saleEa.getText());// 선택된 데이터의 판매량
		hap = stoc + bef;
		// 선택된 열의 판매량과 재고량을 합
	}

	public String replace(String s) {
		String temp = s.replace(",", "");
		String temp2 = temp.replace("원", "");
		return temp2;
	}

	public void se() {
		String code = proCode.getText();
		System.out.println(code);
		Set<String> st = hSal.keySet();
		Iterator<String> it = st.iterator();
		int ori2 = Integer.parseInt(vec.get(3));
		int su = Integer.parseInt(saleEa.getText());
		int ea = ori2 - su;

		// index번호 순서대로
		while (it.hasNext()) {
			String key = it.next();
			SaleTotal value = hSal.get(key);
			if (value.getProCode().equals(code)) {
				int ori = hSal.get(code).getSaleEa();
				ori = ori - ea;
				int tot = ori * hSal.get(code).getProPrice();
				SaleTotal data2 = new SaleTotal(value.getProCode(),
						value.getProName(), value.getProPrice(), ori, tot);
				hSal.put(code, data2);
			}
		}
	}

	public void compute() {
		try {
			int ea = Integer.parseInt(saleEa.getText());
			if (ea < 0) {
				JOptionPane.showMessageDialog(null, "????");
				saleEa.setText("");
				return;
			}

			if (ea == 0) {
				JOptionPane.showMessageDialog(null, "그럴꺼면 반품 하세요");
				saleEa.setText("");
				saleTot.setText("");
				btnModi.setEnabled(false);
				return;
			}
			if (ea > hap) {
				JOptionPane.showMessageDialog(null, "재고수량이 모자랍니다.");
				saleEa.setText("");
				saleTot.setText("");
				btnModi.setEnabled(false);
				return;
			}
			int price = Integer.parseInt(replace(proPrice.getText()));
			int tot = ea * price;
			String str = df.format((double) tot);
			saleTot.setText(str + "원");
			btnModi.setEnabled(true);
		} catch (Exception e) {

		}
	}

	public void ssto() {

		String code = proCode.getText();
		Set<String> st = sto.keySet();
		Iterator<String> it = st.iterator();
		int ori2 = Integer.parseInt(vec.get(3));
		int su = Integer.parseInt(saleEa.getText());
		int ea = ori2 - su;

		// index번호 순서대로
		while (it.hasNext()) {
			String key = it.next();
			StockData value = sto.get(key);
			if (value.getProCode().equals(code)) {
				int ori = sto.get(code).getProEa();
				ori = ori + ea;
				System.out.println(ori);
				StockData data2 = new StockData(value.getProCode(),
						value.getProName(), value.getProPrice(), ori);
				sto.put(code, data2);
			}
		}
	}

	public void modi() {
		try {
			int sCount = Integer.parseInt(saleCount.getText());
			String code = proCode.getText();
			String name = proName.getText();

			int tot = Integer.parseInt(replace(saleTot.getText()));
			int ea = Integer.parseInt(replace(saleEa.getText()));
			if (ea == 0) {
				model.removeRow(index);
				aSal.remove(index);
			}
			int price = Integer.parseInt(replace(proPrice.getText()));
			SaleData data = new SaleData(code, name, price, ea, (price * ea),
					sCount);
			aSal.set(index, data);

			String str = df.format(ea * price);
			model.setValueAt(String.valueOf(ea), index, 3);// 변경할 내용, 행, 열
			model.setValueAt(String.valueOf(str) + "원", index, 4);
			se();
			ssto();
			JOptionPane.showMessageDialog(null, "수정완료");
			dispose();
			save();
		} catch (Exception ex) {
			JOptionPane.showMessageDialog(null, "???????바보임??????");
		}
	}

	public void save() {
		try {
			FileOutputStream fw = new FileOutputStream("SaleList.dat");
			ObjectOutputStream bw = new ObjectOutputStream(fw);
			bw.writeObject(aSal);// 파일저장
			bw.close();
			fw.close();
		} catch (Exception e) {
			System.out.println("SaleList.dat 저장 실패");
		}

		try {
			FileOutputStream fw = new FileOutputStream("SaleTotal.dat");
			ObjectOutputStream bw = new ObjectOutputStream(fw);
			bw.writeObject(hSal);// 파일저장
			bw.close();
			fw.close();
		} catch (Exception e) {
			System.out.println("SaleTotal.dat 저장 실패");
		}

		try {
			FileOutputStream fw = new FileOutputStream("StockList.dat");
			ObjectOutputStream bw = new ObjectOutputStream(fw);
			bw.writeObject(sto);// 파일저장
			bw.close();
			fw.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("StockList.dat 저장 실패");
		}
	}

	public void back() {
		int yn = JOptionPane.showConfirmDialog(null, "반품할꺼임?...");

		if (yn == JOptionPane.NO_OPTION)
			return;
		else if (yn == JOptionPane.YES_NO_OPTION) {

			model.removeRow(index);
			aSal.remove(index);
			dispose();

			String code = proCode.getText();
			System.out.println(code);
			Set<String> st = hSal.keySet();
			Iterator<String> it = st.iterator();
			int su = Integer.parseInt(saleEa.getText());

			// index번호 순서대로
			while (it.hasNext()) {
				String key = it.next();
				SaleTotal value = hSal.get(key);
				if (value.getProCode().equals(code)) {
					int ori = hSal.get(code).getSaleEa();

					int tot = (ori - su) * hSal.get(code).getProPrice();
					SaleTotal data2 = new SaleTotal(value.getProCode(),
							value.getProName(), value.getProPrice(), ori - su,
							tot);
					hSal.put(code, data2);
				}
			}

			ssto2();
			save();
		}
	}

	public void ssto2() {
		String code = proCode.getText();
		Set<String> st = sto.keySet();
		Iterator<String> it = st.iterator();
		int su = Integer.parseInt(saleEa.getText());

		// index번호 순서대로
		while (it.hasNext()) {
			String key = it.next();
			StockData value = sto.get(key);
			if (value.getProCode().equals(code)) {
				int ori = sto.get(code).getProEa();
				StockData data2 = new StockData(value.getProCode(),
						value.getProName(), value.getProPrice(), ori + su);
				sto.put(code, data2);
			}
		}
	}

	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("제품코드");
			label.setBounds(12, 41, 57, 15);
		}
		return label;
	}

	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("제품명");
			lblNewLabel.setBounds(12, 97, 57, 15);
		}
		return lblNewLabel;
	}

	private JLabel getLblNewLabel_2() {
		if (lblNewLabel_2 == null) {
			lblNewLabel_2 = new JLabel("판매날짜");
			lblNewLabel_2.setBounds(12, 125, 57, 15);
		}
		return lblNewLabel_2;
	}

	private JLabel getLblNewLabel_3() {
		if (lblNewLabel_3 == null) {
			lblNewLabel_3 = new JLabel("수량");
			lblNewLabel_3.setBounds(12, 150, 57, 15);
		}
		return lblNewLabel_3;
	}

	private JLabel getLblNewLabel_4() {
		if (lblNewLabel_4 == null) {
			lblNewLabel_4 = new JLabel("판매액");
			lblNewLabel_4.setBounds(12, 175, 57, 15);
		}
		return lblNewLabel_4;
	}

	private JTextField getProCode() {
		if (proCode == null) {
			proCode = new JTextField();
			proCode.setHorizontalAlignment(SwingConstants.CENTER);
			proCode.setEditable(false);
			proCode.setBounds(81, 38, 116, 21);
			proCode.setColumns(10);
		}
		return proCode;
	}

	private JTextField getProName() {
		if (proName == null) {
			proName = new JTextField();
			proName.setHorizontalAlignment(SwingConstants.CENTER);
			proName.setEditable(false);
			proName.setColumns(10);
			proName.setBounds(81, 94, 116, 21);
		}
		return proName;
	}

	private JTextField getSaleDate() {
		if (saleDate == null) {
			saleDate = new JTextField();
			saleDate.setHorizontalAlignment(SwingConstants.CENTER);
			saleDate.setEditable(false);
			saleDate.setColumns(10);
			saleDate.setBounds(81, 122, 116, 21);
		}
		return saleDate;
	}

	private JTextField getSaleEa() {
		if (saleEa == null) {
			saleEa = new JTextField();
			saleEa.setHorizontalAlignment(SwingConstants.CENTER);
			saleEa.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent arg0) {
					compute();
				}
			});
			saleEa.setColumns(10);
			saleEa.setBounds(81, 147, 116, 21);
		}
		return saleEa;
	}

	private JTextField getSaleTot() {
		if (saleTot == null) {
			saleTot = new JTextField();
			saleTot.setHorizontalAlignment(SwingConstants.CENTER);
			saleTot.setEditable(false);
			saleTot.setColumns(10);
			saleTot.setBounds(81, 172, 116, 21);
		}
		return saleTot;
	}

	private JButton getBtnModi() {
		if (btnModi == null) {
			btnModi = new JButton("판매 수정");
			btnModi.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					modi();
				}
			});
			btnModi.setBounds(12, 231, 92, 23);
		}
		return btnModi;
	}

	private JButton getBtnAll() {
		if (btnAll == null) {
			btnAll = new JButton("All반품");
			btnAll.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					back();
				}
			});
			btnAll.setBounds(105, 231, 92, 23);
		}
		return btnAll;
	}

	private JLabel getLblNo() {
		if (lblNo == null) {
			lblNo = new JLabel("No.");
			lblNo.setBounds(12, 13, 57, 15);
		}
		return lblNo;
	}

	private JTextField getSaleCount() {
		if (saleCount == null) {
			saleCount = new JTextField();
			saleCount.setHorizontalAlignment(SwingConstants.CENTER);
			saleCount.setEditable(false);
			saleCount.setColumns(10);
			saleCount.setBounds(81, 10, 116, 21);
		}
		return saleCount;
	}

	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("단가");
			label_2.setBounds(12, 69, 57, 15);
		}
		return label_2;
	}

	private JTextField getTextField_7() {
		if (proPrice == null) {
			proPrice = new JTextField();
			proPrice.setHorizontalAlignment(SwingConstants.CENTER);
			proPrice.setEditable(false);
			proPrice.setColumns(10);
			proPrice.setBounds(81, 66, 116, 21);
		}
		return proPrice;
	}

	private JTextField getStock() {
		if (stock == null) {
			stock = new JTextField();
			stock.setHorizontalAlignment(SwingConstants.CENTER);
			stock.setEditable(false);
			stock.setText((String) null);
			stock.setColumns(10);
			stock.setBounds(81, 200, 116, 21);
		}
		return stock;
	}

	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("재고수량");
			label_1.setBounds(12, 203, 57, 15);
		}
		return label_1;
	}

}